package com.ww.juc.threadpool.terminate;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 如果正在执行的程序处于shutdown或shutdownNow之后处于正在终止但尚未完全终止的过程中
 * 调用方法isTerminating()则返回true
 * 
 * 如果线程池关闭后，所有任务都已完成，则方法isTerminated()返回true
 * 
 * @author wanggw
 * @date 2024-07-12 18:38:41
 *
 */
public class TerminateDemo {

    public static void main(String[] args) throws InterruptedException {
        Runnable1 runnable = new Runnable1("办公室真冷呢");
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 99999, 99999, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        poolExecutor.execute(runnable);
        poolExecutor.execute(runnable);
        poolExecutor.execute(runnable);
        poolExecutor.execute(runnable);
        System.out.println(poolExecutor.isTerminating() + " " + poolExecutor.isTerminated());
        TimeUnit.SECONDS.sleep(1);
        System.out.println(poolExecutor.isTerminating() + " " + poolExecutor.isTerminated());
        TimeUnit.SECONDS.sleep(1);
        System.out.println(poolExecutor.isTerminating() + " " + poolExecutor.isTerminated());
        TimeUnit.SECONDS.sleep(1);
        System.out.println(poolExecutor.isTerminating() + " " + poolExecutor.isTerminated());
        TimeUnit.SECONDS.sleep(1);
        System.out.println(poolExecutor.isTerminating() + " " + poolExecutor.isTerminated());
        TimeUnit.SECONDS.sleep(1);
        System.out.println(poolExecutor.isTerminating() + " " + poolExecutor.isTerminated());
        TimeUnit.SECONDS.sleep(1);
        poolExecutor.shutdown();
        System.out.println(poolExecutor.isTerminating() + " " + poolExecutor.isTerminated());
        System.out.println("shutdown之后...");
        System.out.println(poolExecutor.isTerminating() + " " + poolExecutor.isTerminated());
        TimeUnit.SECONDS.sleep(1);
        System.out.println(poolExecutor.isTerminating() + " " + poolExecutor.isTerminated());
    }
}

class Runnable1 implements Runnable {
    
    private String username;
    
    public Runnable1(String username) {
        this.username = username;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " username = " + username + " begin " + System.currentTimeMillis());
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " username = " + username + " end " + System.currentTimeMillis());
    }
    
}